<?php

namespace app\common\model\Post;

use think\Model;

// 引入软删除的模型
use traits\model\SoftDelete;

class Comment extends Model
{
    //在模型内部去引入软删除
    use SoftDelete;
    //
    protected $name = "post_comment";

    //指定一个自动设置的时间字段
    //开启自动写入
    protected $autoWriteTimestamp = true;

    //设置字段的名字
    protected $createTime = "createtime"; //插入的时候设置的字段名

    //禁止 写入的时间字段
    protected $updateTime = false;

    //设置软删除的字段更新的时间字段
    protected $deleteTime = 'deletetime';

    protected $append = [
        'createtime_text',
        'status_text',
        'like_count',
        'like_list',
        'comment_count'
    ];


    public function getCommentCountAttr($value, $data)
    {
        $id = $data['id'];

        $count = $this->where(['pid' => $id])->count();

        return $count ? $count : 0;
    }
    
    public function getLikeListAttr($value, $data)
    {
        $like = $data['like'];

        if(empty($like))
        {
            return [];
        }

        //把字符串转换数组
        return explode(',', $like);
    }

    //点赞数量
    public function getLikeCountAttr($value, $data)
    {
        $like = $data['like'];

        if(empty($like))
        {
            return 0;
        }

        //把字符串转换数组
        $arr = explode(',', $like);

        //返回数组的长度
        return count($arr);
    }


    public function getCreateTimeTextAttr($value,$data){
        $createtime = isset($data['createtime']) ? trim($data['createtime']) : '';
        if(empty($createtime)){
            return '';
        }
        return date('Y-m-d H:i',$createtime);
    }

    public function getStatusTextAttr($value,$data)
    {
        $statusList = [0 => '未解决',1 => '已解决'];
        $status = isset($data['status']) ? trim($data['status']) : '';
        if($status >= '0'){
            return $statusList[$status];
        }
    }

    public function business(){
        return $this->belongsTo('app\common\model\Business\User','busid','id',[],'LEFT')->setEagerlyType(0);
    }

    public function post(){
        return $this->belongsTo('app\common\model\Post\Post','postid','id',[],'LEFT')->setEagerlyType(0);
    }

    // 递归查询子集的方法
    public function sublist($pid){
        $son = $this->with(['business'])
            ->where(['pid' => $pid])
            ->order(['pid asc','id asc'])
            ->select();

        if(empty($son)){
            return [];
        }

        // 递归循环
        foreach($son as $item){
            $item['children'] = $this->sublist($item['id']);
        }

        return $son;
    }

}
